<?php

namespace app\api\controller;

use app\api\service\JwtAuth;
use app\api\service\UserServer;
use app\common\model\Users;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\facade\Cache;
use think\facade\Db;

class Wechat extends Base
{
    protected $middleware = [
        'app\api\middleware\Api' => ['except' => ['mnpLogin']],
    ];

    protected function get_app()
    {
        return [
            'app_id' => "wxe474bb1488d38822",
            'secret' => "fe854cfe722195c8c4c9fec2a0d505a3",
            'response_type' => 'array',
            'log' => [
                'driver' => 'daily',
                'level' => 'debug', //info  'driver' => 'daily',
                'file' => __DIR__ . '/../../../runtime/wechat.log',
            ],
        ];
    }

    public function mnpLogin()
    {
        try {
            $post = $this->request->post();
            $app = Factory::miniProgram($this->get_app());
            $code = $post['code'];

            $response = $app->auth->session($code);
            if (!isset($response['openid']) || empty($response['openid'])) {
                throw new Exception('获取openID失败');
            }
        } catch (Exception $e) {
            return $this->result([], 0, -1, '登录失败' . $e->getMessage());
        }
        //添加或更新用户
        $user_id = Db::name('users_auth')->alias('au')
            ->join('users u', 'au.user_id=u.id')
            ->where(function ($query) use ($response) {
                $query->whereOr(['au.openid' => $response['openid']]);
                if (isset($response['unionid']) && !empty($response['unionid'])) {
                    $query->whereOr(['au.unionid' => $response['unionid']]);
                }
            })
            ->value('user_id');

        if (empty($user_id)) {
            $user_info = UserServer::createUser($response, 1);
        } else {
            $user_info = UserServer::updateUser($response, 1, $user_id);
        }

        if (empty($user_info)) {
            return $this->result([], 0, -1, '登录失败');
        }

        if ($user_info['status'] != 1) {
            return $this->result([], 0, -1, '用户状态异常');
        }

        // 4. 生成 JWT Token
        try {
            $jwtAuth = JwtAuth::getInstance();
            if (!$jwtAuth) {
                throw new Exception('认证服务不可用');
            }

            // 构建用户信息（仅包含必要字段）
            $userInfoForToken = [
                'user_id' => $user_info['id'],
                'user_name' => $user_info['username'] ?? 'user_' . $user_info['id']
            ];

            // 生成 Token
            $token = $jwtAuth->getToken($userInfoForToken);

            // 附加 Token 到用户信息
            $user_info['token'] = $token;

            // 移除敏感字段
            unset($user_info['id']);
            unset($user_info['status']);

            // 返回成功响应
            return $this->result($user_info, 0, 1, '登录成功');
        } catch (Exception $e) {
            \think\facade\Log::error("JWT生成失败: " . $e->getMessage());
            return $this->result([], 0, -2, '登录失败');
        }

    }

    public function getMobileByMnp()
    {
        Db::startTrans();
        try {
            $post = $this->request->post();
            $app = Factory::miniProgram($this->get_app());
            $code = $post['code'];
            $response = $app->getClient()->httpPostJson('wxa/business/getuserphonenumber',['code' => $code]);

            $phoneNumber = $response['phone_info']['purePhoneNumber'];
            $user_id = $this->getUid();

            $isExist = Users::where([
                ['mobile', '=', $phoneNumber],
                ['id', '<>', $user_id]
            ])->find();
            if (!empty($isExist)) {
                throw new Exception('手机号已被其他账号绑定');
            }

            Users::where(['id' => $user_id])->update(['mobile' => $phoneNumber,'is_new_user' => 0]);
            Db::commit();
            return $this->result([], 0, 1, '获取成功');
        } catch (Exception $e) {
            Db::rollback();
            return $this->result([], 0, 1, '获取失败' . $e->getMessage());
        }
    }

    protected function getUid()
    {
        $jwtAuth = JwtAuth::getInstance();
        return $jwtAuth->getUserId();
    }

    public function updateUser()
    {
        $post = $this->request->post();
        $post['is_new_user'] = 0;
        $post['avatar'] = $post['avatar'] ?? '';
        $post['nickname'] = $post['nickname'] ?? '';
        Users::where(['id' => $this->getUid()])->update($post);
        return $this->result([], 0, 1, '更新成功');
    }
}